<template>
  <div>
    <!-- 两种类型的操作 -->
    <div class="option" >
      <div class="btu" v-if="role=='teacher'">
        <el-popover
          placement="right"
          v-model:visible="visible"
          :width="200"
          trigger="click"
        >
          <template #reference>
            <el-button type="primary" size="large" round 
              >+新建文件夹</el-button
            >
          </template>
          <div>
            <el-input
              v-model="folderName"
              placeholder="输入文件夹名"
            ></el-input>
          </div>
          <div style="text-align: right; margin-top: 10px">
            <el-button size="small" text @click="visible = false"
              >取消</el-button
            >
            <el-button size="small" type="primary" @click="creatFolder"
              >确认</el-button
            >
          </div>
        </el-popover>
        <el-button type="primary" size="large" round plain @click="uploadFile()"
          >上传文件</el-button
        >
      </div>
      <div class="search">
        <el-input
          v-model="input1"
          class="w-50 m-2"
          size="large"
          placeholder="搜索"
          suffix-icon="search"
        />
      </div>
    </div>
    <div class="bread">
      <div>
        <el-breadcrumb separator=">">
          <el-breadcrumb-item>
            <li v-if="navigationStack.length == 1">全部文件</li>
            <a
              v-else-if="navigationStack.length > 1"
              href="javascript:"
              @click="firstFolder()"
              >全部文件</a
            >
          </el-breadcrumb-item>
          <template v-if="navigationStack.length>2">
          <el-breadcrumb-item v-for="(item, index) in navigationStackCumputed(navigationStack.length)">
            <a href="javascript:" @click="changeFolder(index)">{{ item }}</a>
          </el-breadcrumb-item>
          </template>
          <template v-if="navigationStack.length == 2">
            <el-breadcrumb-item>
              <li>{{ navigationStack[1] }}</li>
            </el-breadcrumb-item>
          </template>
        </el-breadcrumb>
      </div>
      <div>
        <div v-show="navigationStack.length > 1">
          <el-button type="primary" size="small" @click="backFolder()"
            >返回上一级目录</el-button
          >
        </div>
        <div style="color: rgb(204, 204, 204); font-size: 12px">
          共{{ showData.length }}个
        </div>
      </div>
    </div>
    <div class="file-box" id="file">
      <el-table :data="showData" border style="width: 100%">
        <el-table-column prop="fileName" label="文件名" width="580">
          <template #default="scope">
            <div class="fileName">
              <div style="width: 75%">
                <img
                  src="http://mooc1-1.chaoxing.com/space/new/images/data/pdf.gif"
                  alt="src"
                  v-if="scope.row.fileSuffix === 'pdf'"
                />
                <img
                  src="http://mooc1-1.chaoxing.com/space/new/images/data/ppt.gif"
                  alt="src"
                  v-else-if="
                    scope.row.fileSuffix === 'ppt' ||
                    scope.row.fileSuffix === 'pptx'
                  "
                />
                <img
                  src="http://mooc1-1.chaoxing.com/space/new/images/data/excl.gif"
                  alt="src"
                  v-else-if="
                    scope.row.fileSuffix === 'xls' ||
                    scope.row.fileSuffix === 'xlsx'
                  "
                />
                <img
                  src="http://mooc1-1.chaoxing.com/space/new/images/data/word.gif"
                  alt="src"
                  v-else-if="scope.row.fileSuffix === 'doc'"
                />
                <img
                  src="http://mooc1-1.chaoxing.com/space/new/images/data/rar.gif"
                  alt="src"
                  v-else-if="scope.row.fileSuffix === 'zip'"
                />
                <img
                  src="http://mooc1-1.chaoxing.com/space/new/images/data/star.gif"
                  alt="src"
                  v-else
                />
                <span
                  :title="scope.row.fileName"
                  @click="childrenFolder(scope.row)"
                  style="
                    display: inline-block;
                    width: 70%;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  "
                  >{{ scope.row.fileName }}</span
                >
              </div>
              <div v-if="role=='teacher'" style="display: none">
                <!-- 是老师身份才加入 -->
                <div v-if="scope.row.file" style="display: flex">
                  <el-popover
                    placement="right"
                    :width="200"
                    trigger="click"
                    :ref="scope.row.dataId"
                    @show="initName(scope.row.fileName)"
                  >
                    <template #reference>
                      <el-button type="primary" text>重命名</el-button>
                    </template>
                    <div>
                      <el-input
                        v-model="fileName"
                        placeholder="输入文件夹名"
                      ></el-input>
                    </div>
                    <div style="text-align: right; margin-top: 10px">
                      <el-button
                        size="small"
                        text
                        @click="cancel(scope.row.dataId)"
                        >取消</el-button
                      >
                      <el-button
                        size="small"
                        type="primary"
                        @click="reNameFile(scope.row)"
                        >确认</el-button
                      >
                    </div>
                  </el-popover>
                  <el-popconfirm
                    confirm-button-text="Yes"
                    cancel-button-text="No"
                    icon-color="#626AEF"
                    title="Are you sure to delete this?"
                    @confirm="deletFile(scope.row)"
                    @cancel="cancelEvent"
                  >
                    <template #reference>
                      <el-button type="primary" text>删除</el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </div>
            </div>
            <!-- 老师权限 -->
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="大小" width="100" />
        <el-table-column prop="creator" label="创建者" width="100" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <div v-if="scope.row.file">
              <el-button type="primary" text disabled @click="preview(scope.row)">预 &nbsp; 览</el-button>
              <el-button
                type="primary"
                text
                @click="downLoad(scope.row.fileName)"
                >下载</el-button
              >
            </div>
            <!-- disable需要根据用户身份进行选择 -->
            <div v-if="!scope.row.file">
              <el-button
                type="primary"
                text
                @click="reNameFloder(scope.row)"
                disabled
                >重命名</el-button
              >
              <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
               
                icon-color="#626AEF"
                title="确定要删除？"
                @confirm="deleteFolder(scope.row)"
                @cancel="cancelEvent()"
              >
                <template #reference>
                  <el-button type="primary" text>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="上传文件" v-model="dialogFormVisible">
      <el-upload
        class="upload-demo"
        drag
        ref="uploadDemo"
        :headers="headerObj"
        action="http://localhost:8088/api/courseData/uploadTest"
        :file-list="fileList"
        :data="courseData"
        :before-upload="beforUpload"
        :on-success="uploadSuccess"
        :on-error="uploadFail"
        :limit="1"
        :on-exceed="exceed"
        :auto-upload="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            files with a size less than 10G
            <el-button
              size="small"
              style="margin-left: 50px"
              @click="dialogFormVisible = false"
              >取 消</el-button
            >
            <el-button size="small" type="primary" @click="upload1"
              >确 定</el-button
            >
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
import {
  getObjectList,
  getCourseById,
  newFolder,
  deleteByPath,
  deleteFolder1,
  reName,
  download,
  fileUrl,
} from "../../api/course.js";
import { ElMessage } from "element-plus";
import { mapGetters } from "vuex";
export default {
  props: ["courseId"],
  setup() {
    const { proxy } = getCurrentInstance();
    // 关于路径的存放
    //导航相对于开始的位置
    const navigationStack = reactive([]);
    //浏览历史保存所有
    const navigationHistoryStack = reactive([]);
    // 新文件夹名称
    const visible = ref(false);
    const folderName = ref("");
    const courseId = ref("");
    // 重命名 文件操作
    const fileName = ref("");
    const tableData = reactive([]);
    const showData = reactive([]);
    const childrenFolder = (item) => {
      console.log(item)
      // 文件夹
      if (!item.file) {
        navigationStack.push(item.fileName);
        let path = navigationStack.join("/") + "/";
        getChildrenFolder(path);
      } else {
        // 文件预览
        //proxy.preview(item)
      //  console.log(proxy)
     //   alert("文件预览，暂未开启");
      }
    };
    const backFolder = () => {
      navigationStack.pop();
      let path = navigationStack.join("/") + "/";
      getChildrenFolder(path);
    };
    const getCurrentTime = (stamp) => {
      let time;
      if (stamp !== undefined) {
        time = new Date(stamp);
      } else {
        time = new Date();
      }
      let d = time.toLocaleDateString();
      let h = time.toLocaleTimeString();
      return `${d} ${h}`;
    };
    const creatFolder = () => {
      if (folderName.value == "") {
        folderName.value = "新建文件夹";
      }
      let Folder = {
        courseId: courseId.value, //课程id
        createTime: "",
        creator: "陈洋名", //创建者 需要根据状态管理进行获取
        dataId: "",
        dataUrl: "",
        file: false,
        fileName: folderName.value, //文件夹名称
        fileSize: "",
        fileSuffix: "",
        parentPath: backPath(), //路径
      };
      newFolder(Folder).then((res) => {
        if (res.code == 200) {
          res.data.createTime = getCurrentTime(res.data.createTime);
          showData.push(res.data);
          visible.value = false;
          ElMessage({
            type: "success",
            message: "文件夹创建成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "文件夹创建失败",
          });
        }
      });
    };
    const cancelEvent = () => {
      console.log("cancel!");
    };
    // 返回当前路径
    const backPath = () => {
      return navigationStack.join("/") + "/";
    };
    // 删除文件夹
    const deleteFolder = (fileData) => {
      let objectName = backPath() + fileData.fileName;
      deleteFolder1(fileData.dataId, objectName).then((res) => {
        if (res.code == 200) {
          showData.splice(showData.indexOf(fileData), 1);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        } else {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        }
      });
    };
    // 删除文件
    const deletFile = (fileData) => {
      //console.log(fileData);
      let objectName = backPath() + fileData.fileName;
      deleteByPath(fileData.dataId, objectName).then((res) => {
        if (res.code == 200) {
          showData.splice(showData.indexOf(fileData), 1);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        } else {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        }
      });
    };
    // 传入当前文件路径，返回其路径下的内容
    const getChildrenFolder = (path) => {
      // 初始化资料目录
      getObjectList(path).then((res) => {
        if (res.code == 200) {
          showData.length = 0;
          res.data.forEach((item) => {
            item.createTime = getCurrentTime(item.createTime);
            showData.push(item);
          });
          //console.log(showData);
        } else {
          ElMessage({
            type: "error",
            message: "获取目录数据失败",
          });
        }
      });
    };
    const reNameFile = (fileData) => {
      // console.log(proxy)
      let objectName = backPath() + fileData.fileName;
      reName(fileData.dataId, fileName.value, objectName).then((res) => {
        if (res.code == 200) {
          showData.splice(showData.indexOf(fileData), 1);
          res.data.createTime = getCurrentTime(res.data.createTime);
          showData.push(res.data);
          proxy.$refs[fileData.dataId].hide();
          ElMessage({
            type: "success",
            message: "重命名成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "重命名失败",
          });
        }
      });
    };
    const initName = (oldFileName) => {
      fileName.value = oldFileName;
    };
    const downLoad = (fileName) => {
      let objectName = backPath() + fileName;
      download(objectName).then((res) => {
        let url = window.URL.createObjectURL(new Blob([res]));
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        // 下载完成移除元素
        document.body.removeChild(link);
        // 释放掉blob对象
        window.URL.revokeObjectURL(url);
      });
    };
    const firstFolder = () => {
      navigationStack.splice(1);
      getChildrenFolder(backPath());
    };
    const changeFolder = (index) => {
      navigationStack.splice(index+2);
      getChildrenFolder(backPath());
    };
    return {
      tableData,
      showData,
      folderName,
      fileName,
      courseId,
      visible,
      navigationStack,
      navigationHistoryStack,
      childrenFolder,
      creatFolder,
      getCurrentTime,
      deleteFolder,
      cancelEvent,
      getChildrenFolder,
      backFolder,
      backPath,
      deletFile,
      reNameFile,
      initName,
      downLoad,
      firstFolder,
      changeFolder,
    };
  },
  // 数据源
  data() {
    return {
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      dialogFormVisible: false,
      courseDetail: {},
      courseData: {
        dataId: "",
        courseId: "",
        creator: "",
        fileName: "",
        dataUrl: "",
        fileSize: "",
        createTime: "",
        isFile: "",
        parentPath: "",
      },
      fileList:[],
       file: "https://jack-chen.oss-cn-chengdu.aliyuncs.com/%E6%96%87%E4%BB%B6/shlab.pdf?Expires=1656571719&OSSAccessKeyId=TMP.3KdaQ8tztcQQcyi3cSUzXfPccUcXyWY9LbeVqsGeRdAHdWQsSpMwwfeGVgj1Vn2KAdoXePc4RvugbJSHPPQS4Efdek8Fa2&Signature=ZvukzoXHgPZ8tPFxOLOTAHm%2BKAc%3D",
      xurl: "https://view.xdocin.com/view?src=",
      ops: {
        // "pdf": true, //word文档尝试以pdf方式显示，默认false
        // "watermark": "XDOC文档预览", //水印文本，显示水印
         "saveable": true, //是否允许保存源文件，默认false
        // "printable": false, //是否允许打印，默认true
        // "copyable": false, //是否允许选择复制内容，默认true
        // "toolbar": false, //是否显示底部工具条，默认true
        // "title": "文档预览", //自定义标题
         "expire": 5, //预览链接有效期，单位分钟，默认永久有效
        // "limit": "1,3", //限制页数，如：“5”表示只显示前5页，“2,5”表示从第2页开始的5页，对pdf/doc/docx/ppt/pptx有效
        // "mtime": 1633093801, //文件修改时间戳（精确到秒）或修改时间（如：2021-10-01 21:10:01），值改变刷新缓存，实时预览
      },
      permanent:"https://view.xdocin.com/view?src=",
      input1:'',
    };
  },
  created() {
    //将捕获到的参数进行首次保存（课程ID）
    this.courseId = this.getParams();
    this.courseData.courseId = this.courseId;
  },
  //生命周期函数---
  mounted() {
    this.getCourseDetail();
  },
  //基本方法
  methods: {
    //获取课程ID
    getParams() {
      const route = useRoute();
      let courseId = route.query.courseId;
      return courseId;
    },
    // 根据课程ID获取课程相关信息 初始化操作 需要考虑文本  路径入栈
    getCourseDetail() {
      let that = this;
      getCourseById(that.courseId).then((res) => {
        if (res.code == 200) {
          that.courseDetail = res.data;
          that.navigationStack.push(res.data.name);
          let path = that.navigationStack.join("/") + "/";
          that.getChildrenFolder(path);
        } else {
          ElMessage({
            type: "error",
            message: "获取课程信息失败",
          });
        }
      });
    },
    navigationStackCumputed (nav) {
      return this.navigationStack.filter((item, index) => 
        index>0&&index<nav
      );
    },
    exceed() {
      ElMessage({
        type: "warning",
        message: "一次只能上传一个文件",
      });
    },
    uploadSuccess(response) {
      this.showData.push(response.data);
      this.fileList=[];
      this.dialogFormVisible = false;
      ElMessage({
        type: "success",
        message: "上传成功",
      });
    },
    uploadFail() {
      ElMessage({
        type: "error",
        message: "上传失败",
      });
        this.fileList=[];
    },
    //确定上传文件 打开框框
    uploadFile() {
      this.dialogFormVisible = true;
    },
    // 对选中文件进行上传
    upload1() {
      //手动提交上传
      this.$refs.uploadDemo.submit();
      this.getChildrenFolder(this.backPath());
    },
    beforUpload(file) {
     this.courseData.creator = this.userName;
      this.courseData.parentPath = this.backPath();
    },
    cancel(dataId) {
      this.$refs[dataId].hide();
    },
    // 预览
    preview(row){
      let path= this.backPath()+ row.fileName;
      fileUrl(path).then((res)=>{
        if(res.code=200)
        {
          this.file=res.data;
          this.newLabel();
        }
      })
    },
    newLabel(){
      this.xurl=this.permanent;
       this.xurl += encodeURIComponent(this.file);
      //传入预览参数
      for (var a in this.ops) {
        this.xurl += "&" + a + "=" + encodeURIComponent(this.ops[a]);
      }
       window.open(this.xurl);
    }

  },
  //计算类型方法和其他方法的区别：有缓存。以内存换时间，适用于频繁使用的计算
  computed: {
    ...mapGetters({
       role: "getRole",
       userName:'getRealName'
    })
  },
};
</script>

<style   scoped>
.option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 50px;
}
.bread {
  margin-top: 20px;
  display: flex;
  height: 40px;
  font-size: 16px;
  line-height: 16px;
  justify-content: space-between;
  align-items: center;
}
.file-box {
  margin-top: 20px;
}
.info {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 50px;
  font: 30px/50px "宋体";
  text-align: center;
  transform: translateY(-50px);
  background: #ccc;
}
.cell span {
  cursor: pointer;
}
.fileName {
  display: flex;
  height: 100%;
  align-content: center;
  justify-content: space-between;
  overflow: hidden;
}
.fileName:hover :nth-child(2) {
  display: inline-block !important;
}
.dialog-footer {
  margin-top: 20px;
}
li {
  list-style: none;
  padding: 0px;
  margin: 0px;
}
a:hover{
  color: rgb(0,204,126);
}
</style>